// https://leetcode.cn/problems/range-sum-query-2d-immutable/
// Created by ade on 2022/10/18.
//
#include <iostream>
#include <vector>

using namespace std;

class NumMatrix {
public:
    vector <vector<int>> m;
    // 这题的难点在于边界的处理
    NumMatrix(vector <vector<int>> &matrix) {
        int row = matrix.size();
        int col = matrix[0].size();
        m.resize(row + 1, vector<int>(col + 1));
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                m[i + 1][j + 1] = m[i][j + 1] + m[i + 1][j] - m[i][j] + matrix[i][j];
            }
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        return m[row2 + 1][col2 + 1] - m[row1][col2 + 1] - m[row2 + 1][col1] + m[row1][col1];
    }
};

int main() {
    vector <vector<int >> nums = {
            {3, 0, 1, 4, 2},
            {5, 6, 3, 2, 1},
            {1, 2, 0, 1, 5},
            {4, 1, 0, 1, 7},
            {1, 0, 3, 0, 5}
    };
    NumMatrix so(nums);
    cout << so.sumRegion(2, 1, 4, 3);

    return 0;
}